package com.example.timetable.dialog;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.widget.DatePicker;

import java.util.Calendar;
import java.util.Date;

/**
 * 修改开学时间
 */
public  class DateEditDialog {

    public static void alterDate(Context context, SharedPreferences sp) {
        //android自带的用于选择日期的小部件
        final DatePicker datePicker = new DatePicker(context);
        //
        long date = sp.getLong("date", 0);
        if(date != 0){
            Calendar c = Calendar.getInstance();
            c.setTime(new Date(date));
            //初始化状态,注意这月份是从零开始数的
            datePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), null);
        }
        //创建一个DatePickerDialog用于包裹日期部件
        new DatePickerDialog.Builder(context)
                .setTitle("选择开学日期")
                .setView(datePicker)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int dayOfMonth = datePicker.getDayOfMonth();
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(year, month, dayOfMonth, 0, 0, 0);
                        Date time = calendar.getTime();
                        sp.edit().putLong("date", time.getTime()).apply();
                    }
                })
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

}
